import { resourceLibraryFolderMock } from './data/library.folder'
import Mock from 'mockjs'
import { getNowDateTime } from '../../utils'
import { handleTree, getTreeNodeChildren, getIdFromArray } from '../../utils/tree'
let resourceLibraryFolderList = resourceLibraryFolderMock()
export default [
  {
    url: '/infra/resource-library-folder/create', // 新增
    method: 'post',
    response: data => {
      insert(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: '/infra/resource-library-folder/update', // 修改
    method: 'put',
    response: data => {
      updateById(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: '/infra/resource-library-folder/rename', // 重命名
    method: 'put',
    response: data => {
      updateById(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: '/infra/resource-library-folder/move', // 移动
    method: 'put',
    response: data => {
      updateById(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: RegExp('/infra/resource-library-folder/delete' + '.*'), // 删除
    method: 'delete',
    response: params => {
      deleteById(params)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: RegExp('/infra/resource-library-folder/list' + '.*'), // 查询列表
    method: 'get',
    response: () => {
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: getList()
      }
    }
  }
]

const getList = () => {
  let result = resourceLibraryFolderList
  return result.filter(item => !item.deleted)
}

const insert = data => {
  resourceLibraryFolderList.unshift({
    ...data.body,
    id: Mock.mock('@natural(100, 99999)'),
    creator: '1',
    create_time: getNowDateTime(),
    updater: '',
    update_time: '',
    deleted: false,
    deleted_time: ''
  })
}

const updateById = data => {
  resourceLibraryFolderList.forEach(item => {
    if (item.id === data.body.id) {
      Object.keys(data.body).forEach(v => {
        item[v] = data.body[v]
      })
      item.updater = '1'
      item.update_time = getNowDateTime()
    }
  })
}

const deleteById = params => {
  const ids = getIdFromArray(getTreeNodeChildren(handleTree(resourceLibraryFolderList), { id: parseInt(params.query.id) }))
  resourceLibraryFolderList.forEach(item => {
    ids.forEach(v => {
      if (item.id === v) {
        item.deleted = true
        item.updater = '1'
        item.update_time = getNowDateTime()
        item.deleted_time = getNowDateTime()
      }
    })
  })
}
